package cn.harry.modular.monitor.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.monitor.domain.SysOperationLog;
import cn.harry.modular.monitor.service.SysOperationLogService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: SysOperationLogController Description: 操作日志
 *
 * @author honghh Date 2020/04/28 11:10 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@Tag(name = "monitor-operlog => 用户操作日志")
@RestController
@RequiredArgsConstructor
@RequestMapping("/monitor/operlog")
public class SysOperationLogController {

    private final SysOperationLogService sysOperationLogService;

    @Operation(summary = "list 分页列表")
    @GetMapping(value = "/list")
    public R<IPage<SysOperationLog>> list(Page<SysOperationLog> page,
                                          SysOperationLog sysOperationLog) {
        return R.success(
                sysOperationLogService.page(page, Wrappers.lambdaQuery(sysOperationLog)
                        .orderByDesc(SysOperationLog::getCreateTime)));
    }

    @Operation(summary = "删除")
    @SysLog(title = "删除指定日志", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        boolean count = sysOperationLogService.removeBatchByIds(Arrays.asList(ids));
        return count ? R.success() : R.failed();
    }

    @Operation(summary = "clean 清空记录")
    @SysLog(title = "清空记录", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public R clean() {
        sysOperationLogService.clean();
        return R.success();
    }

    @Operation(summary = "export 导出")
    @SysLog(title = "导出操作日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public R export(HttpServletResponse response, SysOperationLog sysOperationLog) {
        List<SysOperationLog> list = sysOperationLogService
                .getExportList(sysOperationLog);
        try {
            EasyExcel.write(response.getOutputStream(), SysOperationLog.class)
                    .sheet("操作日志").doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("导出失败 error:{}", e.getMessage());
        }
        return R.failed();
    }

}
